import os
import subprocess
import sys
import shutil
from pathlib import Path


def list_venvs():
    # 指定venvs安装目录
    venv_list = []
    user_home_dir = Path.home()
    venv_base_dir = Path(user_home_dir).joinpath('.venvs')
    venv_list = [d for d in os.listdir(venv_base_dir) 
                    if os.path.isdir(os.path.join(venv_base_dir, d))]
    
    return venv_list

def remove_venv_by_name(venv_name):
    user_home_dir = Path.home()
    venv_base_dir = Path(user_home_dir).joinpath('.venvs')
    venv_path = Path(venv_base_dir).joinpath(venv_name)

    # 删除虚拟环境目录
    shutil.rmtree(venv_path)

    # 删除虚拟环境激活脚本
    batch_dir = Path(r'C:\create_venv')
    quick_activate_script_path = batch_dir.joinpath(f"{venv_name}-activate.bat")
    if os.path.exists(quick_activate_script_path):
        os.remove(quick_activate_script_path)


def remove_venv():
    venv_list = dump_venvs_list()

    # 检查是否找到 Python 环境
    if not venv_list:
        print(f"No venv environments found")
        return
    
    # 读取用户输入的 Python 环境索引
    try:
        selected_index = int(input("Enter the index of Venv to remove: "))
        if selected_index < 0 or selected_index >= len(venv_list):
            raise ValueError
    except ValueError:
        print("Invalid index")
        sys.exit(1)

    selected_venv = venv_list[selected_index]
    print(f"Removing venv: {selected_venv}")
    remove_venv_by_name(selected_venv)


def dump_venvs_list():
    venv_list = list_venvs()

    # 检查是否找到 Python 环境
    if not venv_list:
        print(f"No venv environments found")
        return venv_list
 
    # 显示所有可用的 Python 环境
    print("Available Python environments:")
    for i, venv_name in enumerate(venv_list):
        print(f"{i}: {venv_name:<15} : {venv_name}-activate.bat")
    
    return venv_list

if __name__ == "__main__":
    remove_venv()